package com.baihan.angus.app.game.busshow.ui.main.webview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.baihan.angus.app.game.basic.base.BaseActivity;
import com.baihan.angus.app.game.busshow.BR;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.databinding.ActivityWebviewBinding;
import com.baihan.angus.app.game.common.arouter_path.ArouterAppPath;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebViewClient;

@Route(path = ArouterAppPath.WEBVIEW_ACTIVITY)
public class WebviewActivity extends BaseActivity<ActivityWebviewBinding, WebviewVM> {

    @Autowired(name = "linkUrl")
    String linkUrl;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    private FrameLayout.LayoutParams mWebViewLayoutParams;
    private AgentWeb.PreAgentWeb mCreateAgentWeb;
    private AgentWeb mAgentWeb;
    private Gson gson;

    public WebviewActivity() {
        this.gson = new Gson();
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_webview;
    }

    @Override
    protected int getViewModelId() {
        return BR.webviewVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        mVDBinding.titleView.setLeftOnClickListener(v -> {
            if (!mAgentWeb.back()) {
                finish();
            }
        });

        mWebViewLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mCreateAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(mVDBinding.llRoot, 0, mWebViewLayoutParams)//传入AgentWeb的父控件。
                .useDefaultIndicator(ContextCompat.getColor(this, R.color.textColor32), 2)//设置进度条颜色与高度，-1为默认值，高度为2，单位为dp。
                .setWebViewClient(mWebViewClient)//WebViewClient ， 与 WebView 使用一致 ，但是请勿获取WebView调用setWebViewClient(xx)方法了,会覆盖AgentWeb DefaultWebClient,同时相应的中间件也会失效。
                .setWebChromeClient(wvcc)
                .addJavascriptInterface("webBridge", new JavascriptInterface(this))
                .createAgentWeb();//创建AgentWeb。
        initWb();

        mAgentWeb = mCreateAgentWeb.ready()//设置 WebSettings。
                .go(linkUrl); //WebView载入该url地址的页面并显示。
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);
            view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);

//            webView.setLayerType(View.LAYER_TYPE_NONE, null);
//            ViewGroup.LayoutParams layoutParams = webView.getLayoutParams();
//            layoutParams.height = WebView.LayoutParams.WRAP_CONTENT;
//            layoutParams.width = WebView.LayoutParams.MATCH_PARENT;
//            webView.setLayoutParams(layoutParams);
        }
    };

    public com.just.agentweb.WebChromeClient wvcc = new com.just.agentweb.WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            //title就是网页的title
            //txtTitle.setText("ReceivedTitle:"  title);
            if (!TextUtils.isEmpty(title)) {
                // 设置标题
                mVDBinding.titleView.setTitleText(title);
            } else {
                mVDBinding.titleView.setTitleText("");
            }
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
            return true;
        }
    };

    private void openImageChooserActivity() {
        Intent i = createFileItent();
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    /**
     * 创建选择图库的intent
     *
     * @return
     */
    private Intent createFileItent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
//        intent.setType("image/*");
//        Intent   intent = new Intent(
//                Intent.ACTION_PICK,
//                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.setDataAndType(
//                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                "image/*");
        return intent;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) {
                return;
            }
            //上传文件 点取消需要如下设置。 否则再次点击上传文件没反应
            if (data == null) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(null);
                    uploadMessageAboveL = null;
                }
                return;
            }
            if (uploadMessageAboveL != null) {//5.0以上
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                if (data != null && resultCode == Activity.RESULT_OK) {
                    Uri result = data.getData();
                    Log.e("xxx", "5.0-result=" + result);
                    uploadMessage.onReceiveValue(result);
                    uploadMessage = null;
                }
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        Log.e("xxx", "5.0+ 返回了");
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void call(String js) {  //传递organId
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    }

    private void initWb() {
        mCreateAgentWeb.get().getWebCreator().getWebView().setInitialScale(160);
        WebSettings webSettings = mCreateAgentWeb.get().getWebCreator().getWebView().getSettings();
        //8.0以上关闭google安全浏览模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            webSettings.setSafeBrowsingEnabled(false);
        }

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        mCreateAgentWeb.get().getWebCreator().getWebView().setVerticalScrollBarEnabled(false);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(false); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //运行webview通过URI获取安卓文件
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);

        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setUseWideViewPort(true);//设置加载进来的页面自适应手机屏幕
        webSettings.setLoadWithOverviewMode(true);

        //不使用缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }
}